let id = ''
const App = getApp();
const db = wx.cloud.database();
const _ = db.command;
var tapC= true;
Page({
  data: {
    team: [],
    havePub: false,
    haveAdmit:false,
    vlnListNotAdmit: [] //报名了未录取的用户列表
  },
  onLoad(e) {
    console.log(e.id)
    console.log("openid", App.globalData.openid)
    this.setData({
      team_id: e.id
    })
    this.getMemberAdmit() //获取报名的用户列表

    wx.cloud.database().collection("all_team").doc(e.id)
      .get()
      .then(res => {
        console.log("查询该团队信息", res.data)
        this.setData({
          team: res.data,
        })
        console.log("openid", this.data.team._openid)
        wx.cloud.callFunction({
          name: "getProjectList",
          data: {
            teamOpenid: this.data.team._openid,
            flag:"getTeamProject"
          }
        }).then(res => {
          console.log("获取该团队各项目成功", res.result.data)
          this.setData({
            projectLength:res.result.data.length
          })
        }).catch(err => {
          console.log("获取该团队各项目失败", err)
        })
      })
      .catch(res => {
        console.log("查询失败", res)
      })


  },
  //获取报名参加该组织的用户列表
  getMemberAdmit() {
    db.collection("all_team").doc(this.data.team_id).get()
      .then(res => {
        console.log("被录取的成员列表", res.data.memberAdmit)
        this.setData({
          memberAdmit: res.data.memberAdmit,
          memberNotAdmit: res.data.memberNotAdmit,
        })
        // 判断一下这个用户报名和录取过了没
        if (this.data.memberNotAdmit.findIndex(e => e._id == App.globalData.userInfo._id) != -1) {
          console.log("该用户已报名")
          this.setData({
            havePub: true
          })
        } else if(this.data.memberAdmit.findIndex(e => e._id == App.globalData.userInfo._id) != -1){
          console.log("该用户已录取")
          this.setData({
            haveAdmit:true
          })
        }
      }).catch(err => {
        console.log(err)
      })
  },

  // 点击了报名按钮,(建议等团队申请页完善了再说)
  Sign() {
      if(this.data.havePub == false){
          wx.requestSubscribeMessage({
              tmplIds: ['6XVtwHnBop88Uo_msDmoa8BTeH-ObKLnbyHa_oMSd2w','avzUeNJScbyjO9dhIJ_2_GRfl26zqiX23a00r2b03gw'],
          }).then(res => {
              console.log("授权订阅消息成功", res['6XVtwHnBop88Uo_msDmoa8BTeH-ObKLnbyHa_oMSd2w'])
              //如果点击了允许
              if (res['6XVtwHnBop88Uo_msDmoa8BTeH-ObKLnbyHa_oMSd2w'] === "accept") {
                  console.log("报名用户的openid", App.globalData.openid)
                  wx.cloud.callFunction({
                      name: "sendSubptMessage",
                      data: {
                          openId: App.globalData.openid,
                          teamNickname: this.data.team.teamInfo.teamName,
                          phoneNum: this.data.team.managerInfo.phone,
                          teamId:this.data.team_id,
                          flag: "signInTeam"
                      }
                  }).then(res => {
                      console.log("发送订阅消息云函数调用成功", res)
                      //按钮变成已报名的状态
                      this.setData({
                          havePub: true
                      })

                      //把报名人的头像和名字push到该项目数据库的志愿者列表里
                      console.log("报名用户的_id", App.globalData.userInfo._id)
                      console.log("报名用户的头像图片链接", App.globalData.userInfo.userInfo.avaUrl)
                      console.log("报名用户的名字", App.globalData.userInfo.userInfo.name)
                      db.collection('all_team').doc(this.data.team_id).update({
                              data: {
                                  memberNotAdmit: _.push({
                                      avar: App.globalData.userInfo.userInfo.avaUrl,
                                      name: App.globalData.userInfo.userInfo.name,
                                      _id: App.globalData.userInfo._id,
                                      openid: App.globalData.openid
                                  })
                              }
                          }).then(res => {
                              console.log("把报名人push进该团队待录取列表成功", res)
                          })
                          .catch(err => {
                              console.log("把报名人push进该团队待录取列表失败", err)
                          })
                  }).catch(err => {
                      console.log("发送订阅消息云函数调用失败", err)
                  })
              }
          }).catch(err => {
              console.log("授权订阅消息失败", err)
          })
      }

      //已报名且没过截止日期(点了让他取消报名)
      else if (this.data.havePub == true){
          wx.requestSubscribeMessage({
              tmplIds: ['jY5O2DaVBn6G4wz5cqnphlgWOe_umUXXoTehMR9enB4'],
          }).then(res => {
              console.log("授权取消订阅消息成功", res['jY5O2DaVBn6G4wz5cqnphlgWOe_umUXXoTehMR9enB4'])
              //如果点击了允许
              if (res['jY5O2DaVBn6G4wz5cqnphlgWOe_umUXXoTehMR9enB4'] === "accept") {
                  console.log("取消报名用户的名字", App.globalData.userInfo.userInfo.name)
                  wx.cloud.callFunction({
                      name: "sendSubptMessage",
                      data: {
                          openId: App.globalData.openid,
                          userName: App.globalData.userInfo.userInfo.name,
                          teamNickname: this.data.team.teamInfo.teamName,
                          tips:"取消报名参加该组织成功",
                          teamId:this.data.team_id,
                          flag:"cancelSignInTeam"
                      }
                  }).then(res => {
                      console.log("发送取消订阅消息云函数调用成功", res)
                      //按钮变成未报名的状态
                      this.setData({
                          havePub: false
                      })

                      //把取消报名人从该团队的待录取志愿者列表里删除
                      console.log("报名用户的_id", App.globalData.userInfo._id)
                      db.collection('all_team').doc(this.data.team_id).update({
                        data: {
                          memberNotAdmit: _.pull({
                            _id: App.globalData.userInfo._id
                          })
                        }
                      }).then(res => {
                        console.log("把取消报名人删除成功", res)
                      })
                      .catch(err => {
                        console.log("把取消报名人删除失败", err)
                      })
                  }).catch(err => {
                      console.log("发送取消订阅消息云函数调用失败", err)
                  })
              }
          }).catch(err => {
              console.log("授权取消订阅消息失败", err)
          })

      }
  },
  tapConsult(){
        //判断是否注册和登录
    const registerState = (App.globalData.userInfo.userInfo.ID==undefined) ? false :true;
    const loginState = (App.globalData.userInfo.userInfo.avaUrl==undefined) ? false :true;
    if(!registerState){
          return wx.showToast({
            title: '请先注册',
            icon:'error'
          })
    }else if(!loginState){
          return wx.showToast({
            title: '请先登录',
            icon:'error'
          })
    }
    console.log('tapC',tapC);
    if(tapC==false) return;
    tapC = false;
    const hisUserInfo = this.data.team.teamInfo.teamImg;
    const sid = App.globalData.openid + this.data.team._openid;
    const g = App.globalData.userInfo.userInfo;
    const volunteer= {
      avatarUrl: g.avaUrl,
      nickName: g.name,
      openid: App.globalData.openid
    };
    const x= this.data.team.teamInfo;
    const team={
      avatarUrl: x.teamImg,
      nickName: x.teamName,
      openid: this.data.team._openid
    }
    wx.cloud.callFunction({
      name:"lyc_consult",
      data:{
        type: 'newSession',
        sid:sid,
        volunteer:volunteer,
        team:team, 
      }
    })
    .then((res)=>{
      console.log('点击联系的云函数调用成功',res.result.isSid);
      if(res.result.isSid){
        wx.navigateTo({
          url: '/pages/chatManager/chatManager?session_id=' + sid + '&hisUserInfo=' + hisUserInfo,
        })
      }else{
        wx.showToast({
          title: '联系失败',
          icon:'error'
        })
      }
    })
    .catch((res)=>{
      console.log('点击联系的云函数调用失败',res);
      wx.showToast({
        title: '联系失败',
        icon:'error'
      })
    })
    .finally(()=>{tapC = true;})
  }
})